package com.chookss.video.recommend;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.mine.personal.PersonalHomeActivity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.video.entity.VideoEntity;
import com.chookss.view.CircleImageView;
import com.chookss.wxapi.ShareActivity;
import com.google.gson.reflect.TypeToken;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;

public class LongVediosActivity extends BaseAct {


    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.rvView)
    RecyclerView recyclerView;
    @BindView(R.id.srlView)
    SmartRefreshLayout smrRf;
    @BindView(R.id.ivNone)
    ImageView ivNone;
    @BindView(R.id.tvNone)
    TextView tvNone;
    @BindView(R.id.tvNone2)
    TextView tvNone2;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.llBg)
    LinearLayout llBg;
    private RecommendedAdapter adapter;
    private int currentPage = 1;
    private boolean isEnd = false;//是否到底
    private String videoCatalogCode;
    private int type = 1;//0自己的主页1别人的主页
    private List<VideoEntity> list = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.common_srlview_center);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        videoCatalogCode=getIntent().getStringExtra("videoCate");
        commonTitleTxt.setText("课程");
//        smrRf.setPadding(0, Utils.dip2px(this, 12), 0, 0);
        ivNone.setBackgroundResource(R.drawable.icon_default_no_video);
        tvNone.setText("课程为空");
        tvNone2.setText("暂无视频");
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new RecommendedAdapter(R.layout.item_video_recommend, this, list);
        recyclerView.setAdapter(adapter);
        ((SimpleItemAnimator)recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getData();
            }
        });
        smrRf.autoRefresh();
    }

    private void getData() {
        Map<String, String> allmap = new HashMap<>();
        allmap.put("videoCatalogCode", videoCatalogCode);
        allmap.put("catalogType", "2");
        allmap.put("pageNum", currentPage + "");
        allmap.put("pageSize", "20");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<VideoEntity>>>() {
        }.getType(), null, Urls.selectVideoByCatalogCode, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<List<VideoEntity>>() {
            @Override
            public void onSuccess(List<VideoEntity> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if(smrRf==null||llNone==null){
                    return;
                }
                if (data != null && data.size() > 0) {

                    list.addAll(data);
                    adapter.notifyDataSetChanged();
                    smrRf.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        smrRf.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }

                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    @OnClick(R.id.common_title_back)
    public void onClick() {
        finish();
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    class RecommendedAdapter extends BaseQuickAdapter<VideoEntity, BaseViewHolderEx> {
        private Context context;

        public RecommendedAdapter(int layoutResId, Context context, @Nullable List<VideoEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, VideoEntity item) {
            CircleImageView ivHead = helper.getView(R.id.ivHead);
            RelativeLayout rlTop = helper.getView(R.id.rlTop);
            ImageView ivBg = helper.getView(R.id.ivBg);
            TextView tvTime = helper.getView(R.id.tvTime);
            LinearLayout llFocus = helper.getView(R.id.llFocus);
            ImageView ivFocus = helper.getView(R.id.ivFocus);
            TextView tvNumber = helper.getView(R.id.tvNumber);
            TextView tvTiltle = helper.getView(R.id.tvTiltle);
            TextView tvName = helper.getView(R.id.tvName);
            LinearLayout llShare = helper.getView(R.id.llShare);
            LinearLayout llMore = helper.getView(R.id.llMore);
            LinearLayout llPl = helper.getView(R.id.llPl);
            TextView tvShare = helper.getView(R.id.tvShare);
            TextView tvPl = helper.getView(R.id.tvPl);
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) rlTop.getLayoutParams();
            params.height = Utils.getScreenWidthPixel(LongVediosActivity.this) / 2;
            rlTop.setLayoutParams(params);

            tvTime.setText(Utils.changeTime(item.videoSeconds));
            tvNumber.setText(Utils.changeCounts(item.videoPlayCounts) + "次播放");
            GlideUtils.loadCenterCrop(LongVediosActivity.this, item.videoCoverPath, ivBg, R.drawable.icon_video_long);
            GlideUtils.loadAvatar(LongVediosActivity.this, item.headPhotoThumbUrl, ivHead);
            tvName.setText(item.employeeName);
            if (Utils.isNull(item.courseCode)) {
                tvTiltle.setText(item.videoTitle);
            } else {
                tvTiltle.setText(item.courseName);
            }
            tvShare.setText(Utils.changeCounts(item.videoShareCounts));
            tvPl.setText(Utils.changeCounts(item.videoCommentCounts));
            if ("1".equals(item.youIsfans)) {
                ivFocus.setBackgroundResource(R.drawable.iv_focus_24);
            } else {
                ivFocus.setBackgroundResource(R.drawable.iv_add_24);
            }
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(LongVediosActivity.this, VedioDetailActivity.class);
                    intent.putExtra("video", item);
                    startActivity(intent);
                }
            });
            llPl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(LongVediosActivity.this, VedioDetailActivity.class);
                    intent.putExtra("video", item);
                    intent.putExtra("index",2);
                    startActivity(intent);
                }
            });
            llMore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(LongVediosActivity.this, VedioDetailActivity.class);
                    intent.putExtra("video", item);
                    startActivity(intent);
                }
            });
            ivHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    if (Utils.isNull(item.courseCode)) {
                        Intent intent = new Intent(LongVediosActivity.this, PersonalHomeActivity.class);
                        intent.putExtra("employeeCode", item.employeeCode);
                        startActivity(intent);
                    }

                }
            });
            llFocus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    if ("1".equals(item.youIsfans)) {
                        toFollow(item.employeeCode, "0");
                    }else{
                        toFollow(item.employeeCode, "1");
                    }


                }
            });
            llShare.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    Intent intent = new Intent(context, ShareActivity.class);
                    intent.putExtra("title", item.videoTitle);
                    intent.putExtra("createEmployeeName",item.employeeName);
                    intent.putExtra("content", item.videoKeyWord);
                    intent.putExtra("resourceId", item.videoId);
                    intent.putExtra("videoShareCounts", item.videoShareCounts);
                    intent.putExtra("time", item.videoSeconds);
                    intent.putExtra("picUrl", item.videoCoverPath);
                    intent.putExtra("resourceType", 2);
                    context.startActivity(intent);
                }
            });
        }
    }

    private void toFollow(String employeeCode, String type) {
        Map<String, String> allmap = new HashMap<>();
        allmap.put("employeeCode", employeeCode);
        allmap.put("followStatus", type);
        MyHttpRequest.getDefault().postRequestCompat(null, Urls.toFollow, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) throws Exception {
                JSONObject reObject = new JSONObject(data);
                if ("200".equals(reObject.getString("code"))) {
                    if ("1".equals(type)) {
                        MyToast.show("关注成功");
                        refreshData(employeeCode,"1");
                    } else {
                        MyToast.show("取消关注");
                        refreshData(employeeCode,"0");
                    }

                } else {
                    MyToast.show(reObject.getString("msg"));
                }

            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void refreshData(String employeeCode,String type) {
        for (int i = 0; i < list.size(); i++) {
            if (employeeCode.equals(list.get(i).employeeCode)) {
                list.get(i).youIsfans = type;
                adapter.notifyItemChanged(i);
            }
        }

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
            if (map.containsKey("videoId")) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).videoId.equals(map.get("videoId"))) {
                        if (map.containsKey("totalCommentNum")) {
                            list.get(i).videoCommentCounts = map.get("totalCommentNum");
                            adapter.notifyItemChanged(i);
                        }
                    }
                }
            }
        }
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if (map.containsKey("videoId")) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).videoId.equals(map.get("videoId"))) {
                        if (map.containsKey("videoCollectCounts")) {
                            list.get(i).videoCollectCounts = map.get("videoCollectCounts");
                        }
                        if (map.containsKey("videoLikeCounts")) {
                            list.get(i).videoLikeCounts = map.get("videoLikeCounts");
                        }
                        if (map.containsKey("isCollect")) {
                            list.get(i).isCollect = map.get("isCollect");
                        }
                        if (map.containsKey("isLike")) {
                            list.get(i).isLike = map.get("isLike");
                        }
                        if (map.containsKey("videoPlayCounts")) {
                            list.get(i).videoPlayCounts = map.get("videoPlayCounts");
                            adapter.notifyItemChanged(i);
                        }
                        if (map.containsKey("videoShareCounts")) {
                            list.get(i).videoShareCounts = map.get("videoShareCounts");
                            adapter.notifyItemChanged(i);
                        }
                    }
                }
            }
        }
    }
}
